#
# NRK plugin for XBMC Media center
# Copyright (C) 2009 Victor Vikene  contact: z0py3r@hotmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

import os
import log

global_cache_path = '.'


class PluginIOError( Exception ):
    pass
    
     
def write_to_disk(fp, file, mode='w'):

    log.debug('path %s' % fp)
    try:
        file_handle = open(fp, mode)
        file_handle.write(file)
        file_handle.close()
    except:
        raise PluginIOError('Error writing to disk')
    else:
        return filepath

    
def open_from_disk(fp, mode='r'):
    try:
        fh = open(fp, mode)
        data = fh.read()
        fh.close()
    except:
        raise PluginIOError( 'Error reading file' )
    else:
        return data
    


def has_cache(path, cache_time=None, timeformat='m'):
    if not os.path.isfile(path):
        log.debug('No cache found for %s' % path)
        return
        
    if not cache_time:
        return True
           
    cache_time = int(cache_time)
    if timeformat == 'm':
        time_exp = (24* cache_time * 60)
    else:
        time_exp = (cache_time * 60)
    try:
        mtime = os.path.getmtime(path)
    except:
        log.notice('Could not get mtime for %s'% path)
        mtime = 0  
    if ((time() - time_exp) >= mtime):
        return
    else:
        return True


        
def write(self, url, data, mode=''):
    filepath = os.path.join( global_cache_path, hash( url ) )
    return write_to_disk(filepath, data, 'w'+mode)


def open(self, url, mode=''):
    filepath = os.path.join( global_cache_path, hash( url ) )
    return open_from_disk(filepath, 'r'+mode)